import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Post,
  Query,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';

import { UploadService } from './upload.service';

// 确保 temp 目录存在（可选，diskStorage 会自动创建 destination？不一定，保险起见）
const TEMP_UPLOAD_DIR = join(__dirname, '..', '..', 'uploads', 'temp');
if (!existsSync(TEMP_UPLOAD_DIR)) {
  mkdirSync(TEMP_UPLOAD_DIR, { recursive: true });
}

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadChunk(
    @UploadedFile() file: Express.Multer.File,
    @Body('fileHash') fileHash: string,
    @Body('chunkIndex') chunkIndex: string
  ) {
    if (!file || !fileHash || !chunkIndex) {
      throw new HttpException('No file uploaded', HttpStatus.BAD_REQUEST);
    }
    this.uploadService.saveChunk(
      fileHash,
      parseInt(chunkIndex, 10),
      file.buffer
    );
    return {
      success: true,
    };
  }

  @Get('merge')
  mergeChunks(
    @Query('fileHash') fileHash: string,
    @Query('filename') filename: string
  ) {
    if (!fileHash || !filename) {
      throw new HttpException('No file uploaded', HttpStatus.BAD_REQUEST);
    }

    // 简单验证文件名（防止路径穿越）
    if (!/^[a-zA-Z0-9._-]+\.(mp4|mov|avi|mkv)$/i.test(filename)) {
      throw new HttpException('Invalid filename', HttpStatus.BAD_REQUEST);
    }

    const videoId = Date.now().toString();
    // const finalFilename = `${videoId}.mp4`;
    //const finalPath = this.uploadService.mergeChunks(fileHash, finalFilename);

    // TODO: await this.appService.sendTranscodeTask(videoId, finalPath);

    return {
      videoId,
      message: 'Merge successful, transcoding in progress...',
      playUrl: `/hls/${videoId}/index.m3u8`,
    };
  }
}
